import pymysql
from pymysql.cursors import DictCursor


class DBUtil:
    def __init__(self,
                 host,
                 port,
                 user,
                 password,
                 charset='utf8',
                 database='futureloan',
                 cursorclass = DictCursor,
                 **kw
                 ):

        self.conn = pymysql.connect(
            host='120.78.128.25',
            port = 3306,
            user ='future',
            password = '123456',
            charset ='utf8', #不能写成utf-8
            database ='futureloan',
            cursorclass = DictCursor

        )

        self.cursor = self.conn.cursor()

    def query_one(self, sql, args =  None):
        """查询一条记录"""
        self.cursor.execute(sql, args)
        #事物，数据状态同步
        self.conn.commit()
        return self.cursor.fetchone()

    def query_all(self, sql, args = None):
        self.cursor.execute(sql, args)
        self.conn.commit()
        return self.cursor.fetchall()

    def query(self, sql, args=None, one = True):
        if one:
            return self.query_one(sql, args)
        return self.query_all(sql, args)

    def close(self):
        self.cursor.close()
        self.conn.close()

if __name__ == '__main__':
    db = DBUtil()
    sql = "SELECT * FROM member WHERE id = 10;"
    print(db.query(sql))